import React, { useState, useEffect, useRef } from 'react'
import { NavLink, useNavigate, useParams } from 'react-router-dom'
import { IGoods } from '../../interface'
import API_Home from '../api/home'
import API_Comment from '../api/comment'
import API_shopCar from '../api/shopCar'
import { Swiper, Rate, Button, Popup,Toast } from 'antd-mobile'
import { MinusOutline, HeartFill, StarOutline, UpOutline, TruckOutline, UserSetOutline,MinusCircleOutline,MovieOutline,HeartOutline } from 'antd-mobile-icons'
import { LeftOutline, CloseCircleOutline, UserOutline, ClockCircleOutline } from 'antd-mobile-icons'
import './topic.scss'
import { store } from '../../store'


export default function Topic() {
  const [commentVsb, setCommentVsb] = useState(false)
  const [visible5, setVisible5] = useState(false)
  const [comment, setComment] = useState([])
  const [commentList, setCommentList] = useState({author_img:'',username:'',star:'',content:'',time:''})
  const [buyCount, setCount] = useState(1)
  const [arr, setArr] = useState([])
  const [til, setTil] = useState('立即购买')
  const navigate = useNavigate()
  const { token, _id } = store.getState().userReducer.user
  const params = useParams()
  const [goods_topic, set_topic] = useState<IGoods[]>([])

  const getGoods = async () => {
    let res = await API_Home["getHome"]()
    console.log(res, 'res')
    setArr(res.data.data.filter((item: IGoods) => item._id == params.id)[0].img_detail)
    set_topic(res.data.data)

  }
  const getComment = async () => {
    let res = await API_Comment["getComment"]({ token, goods_id: params.id })
    console.log(res, 'comment')
    setComment(res.data.data)
    setCommentList(res.data.data[0])
  }

  useEffect(() => {
    getGoods()
    getComment()
  }, [])

  const infoRef: any = useRef();

  // console.log(arr.join().split(","), '999')
  let abc = arr.join().split(",")
  const items = abc.map((url: any, index: number) => (
    <Swiper.Item key={index}>
      <div className='content'>
        {<img src={url.substr(1, (url.length - 2))} />}
      </div>
    </Swiper.Item>
  ))

  const shopCarAdd = async (item: IGoods) => {
    let res = await API_shopCar['shopCarAdd']({ ...item, token, user_id: _id })
    console.log(res, '加入购物车')
    Toast.show({
        content: '已加入购物车',
        position: 'top'
    })
    console.log(item)
}

  function handleScroll() {
    document.body.scrollTop = document.documentElement.scrollTop = 0;
  }
  function formatDateTime(dates: any) {
    let date = new Date(dates)
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    // m = m < 10 ? ('0' + m) : m;
    var d = date.getDate();
    // d = d < 10 ? ('0' + d) : d;
    var h = date.getHours();
    var minute = date.getMinutes();
    // minute = minute < 10 ? ('0' + minute) : minute;
    // return y + '-' + m + '-' + d+' '+h+':'+minute;
    return y + '-' + m + '-' + d
  };

  // console.log(goods_topic.filter((item: IGoods) => item._id == params.id).map((item: IGoods) => item.img_foot.map((ele:any)=>ele[1])))
  return (
    <div className='topic'>
      <div className='topic_back'>
        <Button onClick={() => navigate(-1)}><LeftOutline /></Button>
      </div>
      {
        goods_topic.filter((item: IGoods) => item._id == params.id).map((item: IGoods) => <div className='topic_item' key={item._id}>

          <div><Swiper autoplay loop>{items}</Swiper></div>
          <h2>{item.goods_name}</h2>
          <div className='canshu'>

            {item.weight && <div className='guige'>已选择{item.weight}g</div>}
            <span className='price'>￥{item.price}</span>
          </div>
          <div className='tips'>
            <div><i><MinusCircleOutline /></i><span>奶油</span><i><HeartOutline/></i><span>树莓</span><i><MovieOutline/></i><span>柚子</span></div>
            <div><StarOutline />保鲜条件:{item.fresh}℃以下保存</div>
            <div className='tipsButtom'><HeartFill />甜度参考：<Rate readOnly defaultValue={item.sweetness} character={<MinusOutline />} style={{
              '--star-size': '32px',
              '--active-color': '#000',
            }} /></div>
          </div>

          <div className='tabs'>
            <div>
              <i><img src={commentList.author_img} /></i>
              <ul>
                <li>{commentList.username}<span>{formatDateTime(commentList.time)}</span></li>
                <li><Rate value={Number(commentList.star)} allowClear={false} /></li>
                <li>{commentList.content}</li>
              </ul>
            </div>
            <p>
              <button onClick={() => setCommentVsb(true)}>更多评论</button>
            </p>
          </div>
          <div className='share'>
            <span onClick={()=>navigate('/service')}><i></i>客服</span>
            <span><i></i>分享</span>
          </div>

          {
            goods_topic.filter((item: IGoods) => item._id == params.id).map((item: IGoods) => <div className='topic_img' key={item._id}>
              {/* {
                item.img_foot.map((ele:any)=><img src={ele.join().split(",")}></img>)
              } */}
            </div>)
          }

          <div>
            {item.img_detail.map((ele, i) => <img key={i} src={ele} alt="" />)}

          </div>
          <Popup
            afterClose={() => {
              setCount(1)
            }}
            visible={visible5}
            onMaskClick={() => {
              setVisible5(false)
            }}
            bodyStyle={{
              borderTopLeftRadius: '8px',
              borderTopRightRadius: '8px',
              minHeight: '40vh',
            }}
          >
            <p className='uncisibles'><CloseCircleOutline fontSize={24} onClick={() => {
              setVisible5(false)

            }} /></p>
            <p className='topic_name'>{item.goods_name}</p>
            <p className='topic_price'>￥{item.price}</p>
            <div className='tips'>
              <div><UserOutline />适合1人食用</div>
              <div><ClockCircleOutline /> 预计最早配送时间：明天09:30</div>
            </div>
            <div className='specs'>
              {item.weight && <b>商品规格</b>}
              <div className='specs_item'>{item.weight}g/每份</div>

            </div>
            <div className='specs'>
              <b>数量</b>
              <div>
                <Button onClick={() => {
                  if (buyCount <= 1) {
                    setCount(1)
                  } else {
                    setCount(buyCount - 1)
                  }
                }} className='topic_count' size='mini' color='primary' >-</Button>
                <span> {buyCount} </span>
                <Button onClick={() => {
                  setCount(buyCount + 1)
                }} className='topic_count' size='mini' color='primary' >+</Button>
              </div>
            </div>

            {til == '立即购买' ? <NavLink to={'/total'} state={{ items: [{ ...item, count: buyCount }], total: buyCount * item.price }}>
              <Button className='check' shape='default' block size='large' color='primary' >确定</Button></NavLink> :
              <Button onClick={() => {
                shopCarAdd(item)
                setVisible5(false)
              }} className='check' shape='default' block size='large' color='primary' >确定</Button>}


          </Popup>
          <div className='aaa'>
            <Popup
          
              className='more_comment'
              visible={commentVsb}
              onMaskClick={() => {
                setCommentVsb(false)
              }}
              bodyStyle={{
                borderTopLeftRadius: '8px',
                borderTopRightRadius: '8px',
                height: '500px',
                overflowY: 'scroll'
              }}
            >
              <div className='more'>更多评论</div>
              <h3>{item.goods_name}</h3>
              <div className='main'>
                {comment.map((ele: any) => (<div className='comment_list' key={ele._id}>
                  <img src={ele.author_img} />
                  <ul>
                    <li style={{ display: 'flex', justifyContent: 'space-between' }}><span>{ele.username}</span><span>{formatDateTime(ele.time)}</span></li>
                    <li><Rate value={Number(ele.star)} allowClear={false} /></li>
                    <li>{ele.content}</li>
                  </ul>

                </div>))}
              </div>


            </Popup>
          </div>

        </div>)
      }

      <div className='buy'>
        <ul>
          <div onClick={()=>navigate('/service')}>
            <i><UserSetOutline /></i>
            <h5>客服</h5>
          </div>
          <div onClick={()=>navigate('/shopCar')}>
            <i><TruckOutline /></i>
            <h5>购物车</h5>
          </div>
          <li onClick={() => {
            setVisible5(true)
            setTil('立即购买')
          }}>
            立即购买
          </li>
          <li onClick={() => {
            setVisible5(true)
            setTil('加入购物车')
          }}>
            加入购物车
          </li>
        </ul>
      </div>

      <div className='stick' onClick={handleScroll}><UpOutline /></div>
    </div>

  )
}
